import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
  Table,
  Modal,
  message,
  Slider,
  Upload,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Link } from 'dva/router';
import G from '../../utils/g';
import moment from 'moment';
import Uploader from '../Goods/Uploader';


const FormItem = Form.Item;
const {Option} = Select;
const {RangePicker} = DatePicker;
const {TextArea} = Input;


@connect(state => ({
  indexBanner: state.indexBanner,
}))
@Form.create()
export default class BasicForms extends PureComponent {
  state = {
    clearImgs : false,
    detail : {}
  };
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'indexBanner/clear',
    });
  }

  componentDidMount() {
    const {dispatch, location} = this.props;
    this.id = G.getUrlValue('id', location.search);
    if (typeof this.id != 'undefined') {
      dispatch({
        type: 'indexBanner/fetchDetail',
        payload: {
          id: this.id
        }
      })
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    //this.props.form.resetFields();  //重置绑定表单数据
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return false;
      }
      values.img = values.imgs[0].url;
      delete values.imgs;
      if(this.id){values.id = this.id;}

      console.log(values);
      this.props.dispatch({
        type: 'indexBanner/bannerSave',
        payload: values,
      }).then(res=>{
        console.log(res);
        if(res){  //新增才会清除表单,修改不需要
          if(values.id){
            message.success('修改成功');
          }else{
            message.success('新增成功');
            this.props.form.resetFields();  //重置绑定表单数据
            this.setState({
              clearImgs : true,
            });
          }
        }
      })
    });
  };
  bindImgsChange = (file)=> {
    if(file.length == 0){
      this.setState({
        clearImgs : true
      });
    }
    //console.log(this.postData);
  };
  render() {
    const id = this.id || '';
    const {  clearImgs} = this.state;
    const { detail } = this.props.indexBanner;
    const { getFieldDecorator, getFieldValue,} = this.props.form;

    let imgsFileList = [];
    if(!clearImgs && detail.img){
      const uid = G.uuid(16);
      imgsFileList = [{
          uid: uid,
          name: uid,
          status: 'done',
          url: detail.img,
        }]
    }

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const tableItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 17},
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 10, offset: 7},
      },
    };

    return (
      <div>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} style={{marginTop: 8}}>
            <FormItem {...formItemLayout} label="标题">
              {getFieldDecorator('title', {
                initialValue : detail.title,
                rules: [
                  {
                    required: true,
                    message: '请输入Banner标题',
                  },
                ],
              })(<Input placeholder="请输入Banner标题"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="描述">
              {getFieldDecorator('desc', {
                initialValue : detail.desc,
              })(<TextArea placeholder="请输入Banner描述" rows={3}/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="Banner图片" help="规格（375 * 200）">
              {getFieldDecorator('imgs', {
                initialValue : imgsFileList || '',
                rules: [
                  {
                    required: true,
                    message: '请上传Banner图片',
                  },
                ],
              })(
                <Uploader
                  length={1}
                  fileList={imgsFileList}
                  onChange={this.bindImgsChange}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="链接地址">
              {getFieldDecorator('url', {
                initialValue : detail.url,
                rules: [
                  {
                    required: true,
                    message: '请输入链接地址',
                  },
                ],
              })(<Input placeholder="请输入链接地址"/>)}
            </FormItem>
            <FormItem {...formItemLayout} label="请选择权重值" help="用于排序，值越大，排序越靠前">
              <div>
                {getFieldDecorator('weight', {
                  initialValue: detail.weight || 0,
                })(
                  <Slider max={100} min={0} step={1} marks={{ 0: 0, 20:20, 40:40, 60:60, 80:80, 100:100 }} />
                )}
              </div>
            </FormItem>
            <FormItem {...formItemLayout} label="上架状态">
              {
                getFieldDecorator('status', {
                  initialValue: detail.status || 0,
                })(
                  <Radio.Group>
                    <Radio value={0}>放入仓库</Radio>
                    <Radio value={1}>上架</Radio>
                  </Radio.Group>
                )
              }
            </FormItem>
            <FormItem {...submitFormLayout} style={{marginTop: 32}}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{marginLeft: 8}}><Link to={`/index/banner`}>返回</Link></Button>
            </FormItem>
          </Form>
        </Card>

      </div>
    );
  }
}
